package org.groupg.project;

import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.dsl.Disruptor;
import com.lmax.disruptor.util.DaemonThreadFactory;


// 定义事件处理器 1
class LongEventHandler1 implements com.lmax.disruptor.EventHandler<LongEvent> {
    @Override
    public void onEvent(LongEvent event, long sequence, boolean endOfBatch) {
        System.out.println("Handler 1 - Event: " + event.get());
    }
}

// 定义事件处理器 2
class LongEventHandler2 implements com.lmax.disruptor.EventHandler<LongEvent> {
    @Override
    public void onEvent(LongEvent event, long sequence, boolean endOfBatch) {
        System.out.println("Handler 2 - Event: " + event.get());
    }
}

public class DisruptorExample3 {
    public static void main(String[] args) throws InterruptedException {
        // 定义 Ring Buffer 大小
        int bufferSize = 1024;

        // 创建 Disruptor
        Disruptor<LongEvent> disruptor = new Disruptor<>(
                new LongEventFactory(), bufferSize, DaemonThreadFactory.INSTANCE);

        // 注册事件处理器，Handler2 依赖 Handler1
        disruptor.handleEventsWith(new LongEventHandler1()).then(new LongEventHandler2());

        // 启动 Disruptor
        disruptor.start();

        // 获取 Ring Buffer
        RingBuffer<LongEvent> ringBuffer = disruptor.getRingBuffer();

        // 发布事件
        for (long i = 0; i < 10; i++) {
            long sequence = ringBuffer.next();
            try {
                LongEvent event = ringBuffer.get(sequence);
                event.set(i);
            } finally {
                ringBuffer.publish(sequence);
            }
        }

        // 关闭 Disruptor
        disruptor.shutdown();
    }
}